<template>
	<view class="container">
		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading-section">
			<view class="loading-card">
				<view class="loading-spinner"></view>
				<text class="loading-text">正在加载用户信息...</text>
			</view>
		</view>

		<!-- 未登录状态 -->
		<view v-else-if="!isLoggedIn" class="login-section">
			<view class="login-card">
				<image class="login-icon" src="/static/logo.png" mode="aspectFit"></image>
				<text class="login-title">欢迎使用省米停车</text>
				<text class="login-subtitle">请先登录以享受完整服务</text>

				<!-- 协议同意区域 -->
				<view class="agreement-section">
					<view class="agreement-row">
						<view class="agreement-checkbox" @click="toggleAgreement">
							<view class="checkbox" :class="{ 'checked': isAgreementChecked }">
								<text v-if="isAgreementChecked" class="checkbox-icon">✓</text>
							</view>
						</view>
						<view class="agreement-content">
							<text class="agreement-text">我已阅读并同意</text>
							<text class="agreement-link" @click="viewUserAgreement">《用户协议》</text>
							<text class="agreement-text">和</text>
							<text class="agreement-link" @click="viewPrivacyAgreement">《隐私协议》</text>
						</view>
					</view>
				</view>

				<button class="login-btn" :class="{ 'disabled': !isAgreementChecked }" @click="handleWxLogin">
					<text class="login-btn-text">微信一键登录</text>
				</button>
			</view>
		</view>

		<!-- 已登录状态 -->
		<view v-else class="profile-section">
			<!-- 用户信息头部 -->
			<view class="user-header">
				<image class="avatar" :src="userInfo.avatar || '/static/default-avatar.png'" mode="aspectFill"></image>
				<view class="user-info">
					<text class="nickname">{{ userInfo.nickname || '用户' }}</text>
					<view class="phone-container">
						<text class="phone">{{ userInfo.phone || '未绑定手机号' }}</text>
						<button v-if="!userInfo.phone" class="bind-phone-btn" open-type="getPhoneNumber" @getphonenumber="handleGetPhoneNumber">
							绑定手机号
						</button>
					</view>
				</view>
			</view>

			<!-- 功能菜单 -->
			<view class="menu-section">
				<!-- 停车场管理员专用菜单 -->
				<view v-if="isParkingOperator" class="menu-group">
					<view class="menu-item operator-item" @click="navigateTo('/pages/parking-operator/dashboard')">
						<view class="menu-icon">🏢</view>
						<text class="menu-text">停车场管理</text>
						<text class="menu-arrow">></text>
					</view>
					<view class="menu-item operator-item" @click="navigateTo('/pages/parking-operator/orders')">
						<view class="menu-icon">📋</view>
						<text class="menu-text">订单管理</text>
						<text class="menu-arrow">></text>
					</view>
				</view>

				<!-- 普通用户菜单 -->
				<view class="menu-group">
					<view class="menu-item" @click="navigateTo('/pages/vehicles/vehicles')">
						<view class="menu-icon">🚗</view>
						<text class="menu-text">我的车辆</text>
						<text class="menu-arrow">></text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/coupons/coupons')">
						<view class="menu-icon">🎫</view>
						<text class="menu-text">我的优惠券</text>
						<text class="menu-arrow">></text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/coupon-center/coupon-center')">
						<view class="menu-icon">🎁</view>
						<text class="menu-text">领券中心</text>
						<text class="menu-arrow">></text>
					</view>
				</view>

				<view class="menu-group">
					<view class="menu-item" @click="navigateTo('/pages/service/service')">
						<view class="menu-icon">📞</view>
						<text class="menu-text">联系客服</text>
						<text class="menu-arrow">></text>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/about/about')">
						<view class="menu-icon">ℹ️</view>
						<text class="menu-text">关于我们</text>
						<text class="menu-arrow">></text>
					</view>
				</view>

				<view class="menu-group">
					<view class="menu-item logout-item" @click="handleLogout">
						<view class="menu-icon">🚪</view>
						<text class="menu-text logout-text">退出登录</text>
						<text class="menu-arrow">></text>
					</view>
				</view>
			</view>
		</view>

		<!-- 手机号授权弹窗 -->
		<view v-if="showPhoneAuthModal" class="phone-auth-modal">
			<view class="modal-overlay" @click="closePhoneAuthModal"></view>
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">完善手机号信息</text>
					<view class="modal-close" @click="closePhoneAuthModal">×</view>
				</view>
				<view class="modal-body">
					<view class="phone-icon">📱</view>
					<text class="modal-desc">为了给您提供更好的服务，需要获取您的手机号码用于订单通知和身份验证</text>
					<view class="modal-buttons">
						<button class="modal-btn cancel-btn" @click="closePhoneAuthModal">暂不绑定</button>
						<button class="modal-btn auth-btn" open-type="getPhoneNumber" @getphonenumber="handleAutoGetPhoneNumber">
							授权手机号
						</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { wxLogin, bindPhoneNumber } from '../../api/user.js'
import roleManager from '../../utils/roleManager.js'
import { get } from '../../utils/request.js'

// 响应式数据
const isLoggedIn = ref(false)
const userInfo = ref({
	nickname: '',
	avatar: '',
	phone: ''
})
const userRole = ref(null)
const isParkingOperator = ref(false)
const isLoading = ref(true) // 添加加载状态

// 协议相关状态
const isAgreementChecked = ref(false)

// 手机号授权相关状态
const isPhoneAuthPending = ref(false)
const showPhoneAuthModal = ref(false)

// 开发环境检测
const isDevelopment = ref(false)

// 检测是否为开发环境
const checkDevelopmentMode = () => {
	// #ifdef MP-WEIXIN
	try {
		const accountInfo = uni.getAccountInfoSync()
		isDevelopment.value = accountInfo.miniProgram.envVersion === 'develop' ||
			accountInfo.miniProgram.envVersion === 'trial'
	} catch (error) {
		isDevelopment.value = true // 获取失败时默认为开发环境
	}
	// #endif

	// #ifndef MP-WEIXIN
	isDevelopment.value = true // 非微信环境默认为开发环境
	// #endif
}

// 检查登录状态
const checkLoginStatus = async () => {
	try {
		isLoading.value = true // 开始加载

		const token = uni.getStorageSync('token')
		const storedUserInfo = uni.getStorageSync('userInfo')

		if (token && storedUserInfo) {
			// 先设置基本用户信息
			try {
				userInfo.value = JSON.parse(storedUserInfo)
			} catch (parseError) {
				console.warn('解析用户信息失败:', parseError)
				// 清除损坏的数据
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('token')
				isLoggedIn.value = false
				return
			}

			// 异步检查用户角色，完成后再设置登录状态
			await checkUserRole()

			// 所有信息加载完成后才设置为已登录
			isLoggedIn.value = true

			// 检查是否需要显示手机号授权弹窗（延迟执行，确保页面已渲染）
			setTimeout(() => {
				checkPhoneAuthRequired()
			}, 500)
		} else {
			isLoggedIn.value = false
			isParkingOperator.value = false
			userRole.value = null
		}
	} catch (error) {
		console.error('检查登录状态失败:', error)
		isLoggedIn.value = false
		isParkingOperator.value = false
		userRole.value = null
	} finally {
		isLoading.value = false // 结束加载
	}
}

// 检查是否需要手机号授权
const checkPhoneAuthRequired = () => {
	// 只有在已登录且没有手机号且弹窗未显示时才显示
	if (isLoggedIn.value && !userInfo.value.phone && !showPhoneAuthModal.value) {
		console.log('📱 检测到用户未绑定手机号，显示授权弹窗')
		showPhoneAuthModal.value = true
	}
}

// 检查用户角色
const checkUserRole = async () => {
	try {
		// 使用初始化方法，优先使用本地缓存
		const roleInfo = await roleManager.initUserRole()
		userRole.value = roleInfo
		isParkingOperator.value = roleInfo.role_type === 'parking_operator'

		console.log('用户角色:', roleInfo.role_type)
		if (isParkingOperator.value) {
			console.log('停车场管理员 - 管理停车场:', roleInfo.parking_lot_name)
		}
	} catch (error) {
		console.error('检查用户角色失败:', error)
		isParkingOperator.value = false
		userRole.value = {
			role_type: 'user',
			permissions: ['view_own_orders', 'create_booking', 'manage_vehicles']
		}
	}
}

// 协议相关方法
const toggleAgreement = () => {
	isAgreementChecked.value = !isAgreementChecked.value
}

const viewUserAgreement = () => {
	uni.navigateTo({
		url: '/pages/agreement/agreement?type=user'
	})
}

const viewPrivacyAgreement = () => {
	uni.navigateTo({
		url: '/pages/agreement/agreement?type=privacy'
	})
}

// 处理获取手机号（手动点击绑定）
const handleGetPhoneNumber = async (e: any) => {
	await processPhoneAuth(e)
}

// 处理自动获取手机号（登录后弹窗）
const handleAutoGetPhoneNumber = async (e: any) => {
	const success = await processPhoneAuth(e)
	if (success) {
		// 授权成功后关闭弹窗
		showPhoneAuthModal.value = false
	}
}

// 通用的手机号授权处理逻辑
const processPhoneAuth = async (e: any) => {
	try {
		console.log('📱 获取手机号事件:', e)
		
		// 检查用户是否拒绝授权
		if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
			uni.showToast({
				title: '您拒绝了手机号授权',
				icon: 'none',
				duration: 2000
			})
			return false
		}
		
		// 检查是否获取到code
		if (e.detail.errMsg !== 'getPhoneNumber:ok' || !e.detail.code) {
			uni.showToast({
				title: '获取手机号失败',
				icon: 'none',
				duration: 2000
			})
			return false
		}
		
		// 显示加载提示
		uni.showLoading({
			title: '绑定中...',
			mask: true
		})
		
		// 调用后端接口绑定手机号
		const response = await bindPhoneNumber(e.detail.code)
		
		if (response.success) {
			// 更新本地用户信息
			userInfo.value = response.data.userInfo
			uni.setStorageSync('userInfo', JSON.stringify(response.data.userInfo))
			
			uni.showToast({
				title: '手机号绑定成功',
				icon: 'success',
				duration: 2000
			})
			return true
		} else {
			throw new Error(response.message || '绑定手机号失败')
		}
		
	} catch (error) {
		console.error('绑定手机号失败:', error)
		uni.showToast({
			title: error.message || '绑定手机号失败，请重试',
			icon: 'none',
			duration: 2000
		})
		return false
	} finally {
		uni.hideLoading()
	}
}

// 关闭手机号授权弹窗
const closePhoneAuthModal = () => {
	showPhoneAuthModal.value = false
}

// 微信登录处理
const handleWxLogin = async () => {
	try {
		// 检查是否同意协议
		if (!isAgreementChecked.value) {
			uni.showToast({
				title: '请先同意用户协议和隐私协议',
				icon: 'none',
				duration: 2000
			})
			return
		}

		// 显示加载提示
		uni.showLoading({
			title: '登录中...',
			mask: true
		})

		// 清除可能存在的旧token，确保使用新的登录流程
		uni.removeStorageSync('token')
		uni.removeStorageSync('userInfo')

		// 获取微信登录凭证
		const loginRes = await new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: resolve,
				fail: reject
			})
		})

		if (!loginRes.code) {
			throw new Error('获取微信登录凭证失败')
		}

		// 获取用户信息（可选）
		let wxUserInfo = {}
		try {
			const userInfoRes = await new Promise((resolve, reject) => {
				uni.getUserInfo({
					provider: 'weixin',
					success: resolve,
					fail: reject
				})
			})
			wxUserInfo = userInfoRes.userInfo
		} catch (error) {
			console.log('获取用户信息失败，使用默认信息:', error)
		}

		// 调用后端登录接口
		const response = await wxLogin(loginRes.code, wxUserInfo)

		if (response.success) {
			console.log(response.data)
			// 保存登录信息
			uni.setStorageSync('token', response.data.token)
			uni.setStorageSync('userInfo', JSON.stringify(response.data.userInfo))
			
			// 更新页面状态
			isLoggedIn.value = true
			userInfo.value = response.data.userInfo

			// 检查是否需要绑定手机号
			if (!response.data.userInfo.phone) {
				console.log('📱 检测到用户未绑定手机号，准备自动授权')
				// 延迟一下，让登录成功提示显示完
				setTimeout(() => {
					showPhoneAuthModal.value = true
				}, 1500)
			}

			uni.showToast({
				title: '登录成功',
				icon: 'success',
				duration: 1000
			})
		} else {
			throw new Error(response.message || '登录失败')
		}
	} catch (error) {
		console.error('微信登录失败:', error)
		uni.showToast({
			title: error.message || '登录失败，请重试',
			icon: 'none',
			duration: 2000
		})
	} finally {
		uni.hideLoading()
	}
}

// 测试开发环境Token状态
const testDevToken = async () => {
	try {
		uni.showLoading({
			title: '测试中...',
			mask: true
		})

		// 检查本地Token
		const token = uni.getStorageSync('token')
		const storedUserInfo = uni.getStorageSync('userInfo')

		console.log('🔍 Token检测结果:')
		console.log('Token存在:', !!token)
		console.log('Token长度:', token ? token.length : 0)
		console.log('用户信息存在:', !!storedUserInfo)

		if (token) {
			console.log('Token前50字符:', token.substring(0, 50) + '...')
		}

		if (storedUserInfo) {
			console.log('用户信息:', JSON.parse(storedUserInfo))
		}

		// 测试一个需要认证的接口（使用管理员profile接口）
		try {
			const response = await get('/api/admin/profile')
			console.log('✅ API测试成功:', response)

			uni.showModal({
				title: 'Token测试结果',
				content: `Token状态: 正常\n用户ID: ${response.data.id}\n用户名: ${response.data.username}\n超级管理员: ${response.data.is_super_admin ? '是' : '否'}\nAPI调用: 成功`,
				showCancel: false
			})
		} catch (apiError) {
			console.error('❌ API测试失败:', apiError)

			uni.showModal({
				title: 'Token测试结果',
				content: `Token状态: ${token ? '存在但可能无效' : '不存在'}\nAPI调用: 失败\n错误: ${apiError.message}`,
				showCancel: false
			})
		}

	} catch (error) {
		console.error('Token测试出错:', error)
		uni.showToast({
			title: '测试失败',
			icon: 'error',
			duration: 2000
		})
	} finally {
		uni.hideLoading()
	}
}

// 退出登录
const handleLogout = () => {
	uni.showModal({
		title: '提示',
		content: '确定要退出登录吗？',
		success: (res: any) => {
			if (res.confirm) {
				// 清除本地存储
				uni.removeStorageSync('token')
				uni.removeStorageSync('userInfo')

				// 更新页面状态
				isLoggedIn.value = false
				userInfo.value = {
					nickname: '',
					avatar: '',
					phone: ''
				}

				uni.showToast({
					title: '已退出登录',
					icon: 'success',
					duration: 2000
				})
			}
		}
	})
}

// 页面导航
const navigateTo = (url: string) => {
	uni.navigateTo({
		url,
		fail: (error: any) => {
			console.error('页面跳转失败:', error)
			uni.showToast({
				title: '页面暂未开放',
				icon: 'none',
				duration: 2000
			})
		}
	})
}

// 生命周期
onMounted(() => {
	console.log('我的页面加载完成')
	checkDevelopmentMode()
	checkLoginStatus()
})

// 页面显示时重新检查登录状态
onShow(() => {
	console.log('我的页面显示')
	// 只有在不是加载状态时才重新检查，避免重复调用
	if (!isLoading.value) {
		checkLoginStatus()
	}
})
</script>

<style scoped>
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

/* 登录部分样式 */
.login-section {
	display: flex;
	align-items: center;
	justify-content: center;
	min-height: 100vh;
	padding: 40rpx;
}

.login-card {
	background: white;
	border-radius: 20rpx;
	padding: 60rpx 40rpx;
	text-align: center;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	width: 100%;
	max-width: 500rpx;
}

.login-icon {
	width: 120rpx;
	height: 120rpx;
	margin-bottom: 30rpx;
}

.login-title {
	display: block;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.login-subtitle {
	display: block;
	font-size: 28rpx;
	color: #666;
	margin-bottom: 40rpx;
}

/* 协议同意区域样式 */
.agreement-section {
	margin-bottom: 40rpx;
	text-align: left;
}

.agreement-row {
	display: flex;
	align-items: flex-start;
	justify-content: flex-start;
}

.agreement-checkbox {
	display: flex;
	align-items: center;
	margin-right: 16rpx;
	flex-shrink: 0;
}

.checkbox {
	width: 32rpx;
	height: 32rpx;
	border: 2rpx solid #ddd;
	border-radius: 6rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
}

.checkbox.checked {
	background-color: #007AFF;
	border-color: #007AFF;
}

.checkbox-icon {
	color: white;
	font-size: 20rpx;
	font-weight: bold;
}

.agreement-content {
	flex: 1;
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	line-height: 1.5;
}

.agreement-text {
	font-size: 26rpx;
	color: #666;
	margin-right: 8rpx;
}

.agreement-link {
	font-size: 26rpx;
	color: #007AFF;
	text-decoration: underline;
	margin: 0 4rpx;
}

.login-btn {
	background: linear-gradient(135deg, #007AFF, #5AC8FA);
	color: white;
	border: none;
	border-radius: 50rpx;
	padding: 24rpx 60rpx;
	font-size: 32rpx;
	width: 100%;
	margin: 0;
	transition: opacity 0.3s ease;
}

.login-btn.disabled {
	opacity: 0.5;
	background: #ccc;
}

.login-btn-text {
	color: white;
	font-weight: bold;
}

/* 加载状态样式 */
.loading-section {
	display: flex;
	justify-content: center;
	align-items: center;
	min-height: 100vh;
	background-color: #f5f5f5;
}

.loading-card {
	background: white;
	border-radius: 20rpx;
	padding: 60rpx 40rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	display: flex;
	flex-direction: column;
	align-items: center;
}

.loading-spinner {
	width: 60rpx;
	height: 60rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #007AFF;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 30rpx;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.loading-text {
	font-size: 28rpx;
	color: #666;
	text-align: center;
}

/* 用户信息部分样式 */
.profile-section {
	padding: 0;
}

.user-header {
	background: linear-gradient(135deg, #007AFF, #5AC8FA);
	padding: 60rpx 40rpx 40rpx;
	display: flex;
	align-items: center;
	color: white;
}

.avatar {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	margin-right: 30rpx;
	border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.user-info {
	flex: 1;
}

.nickname {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.phone-container {
	display: flex;
	align-items: center;
	justify-content: space-between;
	width: 100%;
}

.phone {
	display: block;
	font-size: 28rpx;
	opacity: 0.8;
	flex: 1;
}

.bind-phone-btn {
	background: rgba(255, 255, 255, 0.2);
	color: white;
	border: 1rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 20rpx;
	padding: 8rpx 16rpx;
	font-size: 24rpx;
	margin-left: 20rpx;
	transition: background 0.3s ease;
}

.bind-phone-btn:active {
	background: rgba(255, 255, 255, 0.3);
}

/* 菜单部分样式 */
.menu-section {
	padding: 20rpx;
}

.menu-group {
	background: white;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.menu-item {
	display: flex;
	align-items: center;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
	transition: background-color 0.3s;
}

.menu-item:last-child {
	border-bottom: none;
}

.menu-item:active {
	background-color: #f5f5f5;
}

.menu-icon {
	font-size: 36rpx;
	margin-right: 30rpx;
	width: 40rpx;
	text-align: center;
}

.menu-text {
	flex: 1;
	font-size: 32rpx;
	color: #333;
}

.logout-text {
	color: #ff4757;
}

.menu-arrow {
	font-size: 28rpx;
	color: #ccc;
}

.logout-item .menu-arrow {
	color: #ff4757;
}

/* 停车场管理员专用菜单样式 */
.operator-item {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	margin-bottom: 2rpx;
}

.operator-item .menu-text {
	color: white;
	font-weight: bold;
}

.operator-item .menu-arrow {
	color: white;
}

.operator-item:active {
	background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

/* 开发环境测试按钮样式 */
.dev-test-item {
	background-color: #f8f9fa;
	border: 2rpx dashed #007AFF;
}

.dev-test-item .menu-text {
	color: #007AFF;
	font-weight: bold;
}

.dev-test-item .menu-arrow {
	color: #007AFF;
}

/* 手机号授权弹窗样式 */
.phone-auth-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 9999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.modal-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
}

.modal-content {
	position: relative;
	background: white;
	border-radius: 20rpx;
	width: 600rpx;
	max-width: 90%;
	box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.2);
}

.modal-header {
	position: relative;
	padding: 40rpx 40rpx 20rpx;
	text-align: center;
	border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.modal-close {
	position: absolute;
	top: 20rpx;
	right: 30rpx;
	width: 60rpx;
	height: 60rpx;
	font-size: 40rpx;
	color: #999;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
}

.modal-body {
	padding: 40rpx;
	text-align: center;
}

.phone-icon {
	font-size: 80rpx;
	margin-bottom: 30rpx;
}

.modal-desc {
	display: block;
	font-size: 28rpx;
	color: #666;
	line-height: 1.6;
	margin-bottom: 50rpx;
}

.modal-buttons {
	display: flex;
	gap: 20rpx;
}

.modal-btn {
	flex: 1;
	padding: 24rpx 40rpx;
	border-radius: 50rpx;
	font-size: 32rpx;
	border: none;
}

.cancel-btn {
	background: #f5f5f5;
	color: #666;
}

.auth-btn {
	background: linear-gradient(135deg, #007AFF, #5AC8FA);
	color: white;
}

.modal-btn:active {
	opacity: 0.8;
}
</style>
